.TH std::optional::value 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::optional::value \- std::optional::value

.SH Synopsis
   constexpr T& value() &;               \fB(1)\fP \fI(since C++17)\fP
   constexpr const T& value() const &;
   constexpr T&& value() &&;             \fB(2)\fP \fI(since C++17)\fP
   constexpr const T&& value() const &&;

   If *this contains a value, returns a reference to the contained value.

   Otherwise, throws a std::bad_optional_access exception.

.SH Parameters

   \fI(none)\fP

.SH Return value

   A reference to the contained value.

.SH Exceptions

   std::bad_optional_access if *this does not contain a value.

.SH Notes

   The dereference operator operator*() does not check if this optional contains a
   value, which may be more efficient than value().

.SH Example


// Run this code

 #include <iostream>
 #include <optional>

 int main()
 {
     std::optional<int> opt = {};

     try
     {
         [[maybe_unused]] int n = opt.value();
     }
     catch(const std::bad_optional_access& e)
     {
         std::cout << e.what() << '\\n';
     }

     try
     {
         opt.value() = 42;
     }
     catch(const std::bad_optional_access& e)
     {
         std::cout << e.what() << '\\n';
     }

     opt = 43;
     std::cout << *opt << '\\n';

     opt.value() = 44;
     std::cout << opt.value() << '\\n';
 }

.SH Output:

 bad optional access
 bad optional access
 43
 44

.SH See also

                       returns the contained value if available, another value
   value_or            otherwise
                       \fI(public member function)\fP
   operator->          accesses the contained value
   operator*           \fI(public member function)\fP
   bad_optional_access exception indicating checked access to an optional that doesn't
   \fI(C++17)\fP             contain a value
                       \fI(class)\fP
